package com.frinder.util;

import org.dozer.DozerConverter;
import org.dozer.converters.DateConverter;
import org.dozer.converters.DateFormatContainer;
import org.dozer.converters.StringConverter;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by kiktech on 2017/5/10.
 */
public class MyDateConverter extends DozerConverter<String, Date> {

    private static final String DATE_FORMAT_DAY = "yyyy-MM-dd";
    private static final String DATE_FORMAT_HOUR = "yyyy-MM-dd HH";
    private static final String DATE_FORMAT_MINUTE = "yyyy-MM-dd HH:mm";
    private static final String DATE_FORMAT_SECOND = "yyyy-MM-dd HH:mm:ss";

    private static final DateConverter DATE_CONVERTER_DAY = new DateConverter(new SimpleDateFormat(DATE_FORMAT_DAY));

    private static final DateConverter DATE_CONVERTER_HOUR = new DateConverter(new SimpleDateFormat(DATE_FORMAT_HOUR));

    private static final DateConverter DATE_CONVERTER_MINUTE = new DateConverter(new SimpleDateFormat(DATE_FORMAT_MINUTE));

    private static final DateConverter DATE_CONVERTER_SECOND = new DateConverter(new SimpleDateFormat(DATE_FORMAT_SECOND));

    private static final StringConverter STRING_CONVERTER = new StringConverter(new DateFormatContainer(DATE_FORMAT_SECOND));

    public MyDateConverter() {
        super(String.class, Date.class);
    }

    @Override
    public Date convertTo(String s, Date date) {
        s = StringUtils.isEmpty(s) ? "" : s;
        DateConverter converter;
        if (s.length() == DATE_FORMAT_DAY.length()) {
            converter = DATE_CONVERTER_DAY;
        } else if (s.length() == DATE_FORMAT_HOUR.length()) {
            converter = DATE_CONVERTER_HOUR;
        } else if (s.length() == DATE_FORMAT_MINUTE.length()) {
            converter = DATE_CONVERTER_MINUTE;
        } else if (s.length() == DATE_FORMAT_SECOND.length()) {
            converter = DATE_CONVERTER_SECOND;
        } else {
            converter = DATE_CONVERTER_DAY;
        }
        return (Date) converter.convert(Date.class, s);
    }

    @Override
    public String convertFrom(Date date, String s) {
        return (String) STRING_CONVERTER.convert(String.class, date);
    }

}
